package com.wj.LightActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class LightActivity extends Activity implements OnTouchListener {

	private ImageButton light;
	private ImageButton set;
	private ImageButton flash;
	private View background;
	private long exitTime = 0;
	SaveInstance saveInstance = new SaveInstance();
	private boolean autoOff;// 关灯退出
	private boolean animOpen;// 开启动画
	private boolean getScreenOn;// 开启屏幕灯
	private Animation operatingAnim;
	private int colorNumber;
	private static final int BITS_PER_UNIT = 8;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_light);

		light = (ImageButton) findViewById(R.id.light);
		set = (ImageButton) findViewById(R.id.set);
		flash = (ImageButton) findViewById(R.id.flash);
		background = (View) findViewById(R.id.background);
		background.setOnTouchListener(this);
		light.setOnClickListener(new ButtonListener());
		set.setOnClickListener(new ButtonListener());
		flash.setOnClickListener(new ButtonListener());
		saveInstance.getScreenStatus(this);
		if (saveInstance.getAutoOn(this)) {
			openLight();
		}
		operatingAnim = AnimationUtils.loadAnimation(this, R.anim.tip);
		LinearInterpolator lin = new LinearInterpolator();
		operatingAnim.setInterpolator(lin);
	}
	
	private static int position(int idx) {
		//bits big-endian in each unit
		return 1 << (BITS_PER_UNIT-1-(idx % BITS_PER_UNIT));
	}

	@Override
	protected void onResume() {
		super.onResume();
		autoOff = saveInstance.getAutoOff(this);
		animOpen = saveInstance.getAnimOpen(this);
		getScreenOn = saveInstance.getScreenOn(this);
		if (!saveInstance.getOpenNotify(this).equals("unknown")) {
			Config.openToast = saveInstance.getOpenNotify(this);
		}
		if (!saveInstance.getCloseNotify(this).equals("unknown")) {
			Config.closeToast = saveInstance.getCloseNotify(this);
		}
	}

	class ButtonListener implements OnClickListener {

		@Override
		public void onClick(View view) {
			if(!Config.hasFlash) {
				Toast.makeText(LightActivity.this, "没有检测到闪光灯", Toast.LENGTH_LONG).show();
				return;
			}
			if (view == light) {
				if (!Config.isOpen) {
					if(Config.isFlash) stopFlash();
					openLight();
				} else {
					closeLight();
				}
			} else if (view == set) {
				startActivity(new Intent(LightActivity.this, SetActivity.class));
				overridePendingTransition(R.anim.slide_in_left,
						R.anim.slide_out_left);
			} else if (view == flash) {
				if (!Config.isFlash) {
					if(Config.isOpen) closeLight();
					openFlash();
				} else {
					stopFlash();
				}
			}
		}
	}

	/**
	 * 打开闪动模式
	 */
	private void openFlash() {
		Intent intent = new Intent(LightActivity.this, MyLightService.class);
		intent.putExtra("intent", "isFlash");
		startService(intent);
		if (operatingAnim != null && animOpen) {
			light.clearAnimation();
			flash.startAnimation(operatingAnim);
		}
	}

	/**
	 * 关闭闪动模式
	 */
	private void stopFlash() {
		Intent intent = new Intent(LightActivity.this, MyLightService.class);
		stopService(intent);
		flash.clearAnimation();
	}

	private void openLight() {
		Toast.makeText(LightActivity.this, Config.openToast, Toast.LENGTH_SHORT)
				.show();
		Intent intent = new Intent(LightActivity.this, MyLightService.class);
		intent.putExtra("intent", "isLight");
		startService(intent);
		background.setBackgroundResource(R.drawable.light);
		if (operatingAnim != null && animOpen) {
			flash.clearAnimation();
			light.startAnimation(operatingAnim);
		}
	}

	private void closeLight() {
		Toast.makeText(LightActivity.this, Config.closeToast,
				Toast.LENGTH_SHORT).show();
		Intent intent = new Intent(LightActivity.this, MyLightService.class);
		stopService(intent);
		background.setBackgroundColor(Color.parseColor(color[0]));
		light.clearAnimation();
		if (autoOff) {
			finish();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			exits();
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 退出应用程序
	 */
	private void exits() {
		if ((System.currentTimeMillis() - exitTime) > 2000) {
			exitTime = System.currentTimeMillis();
			Toast.makeText(LightActivity.this, "再按一次返回键，退出程序",
					Toast.LENGTH_SHORT).show();
		} else {
			finish();
		}
	}

	String color[] = { "#000000", "#d0d0d0", "#ECFFFF", "#FFFFFF" };

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if (!getScreenOn)
			return true;
		float tempX = set.getX();
		float tempY = set.getY();
		float touchX = event.getX();
		float touchY = event.getY();
		System.out.println("touchX: "+touchX);
		if (Math.abs(touchX - tempX) > 60 && Math.abs(touchY - tempY) > 60) {
			colorNumber++;
			if (colorNumber >= color.length) {
				colorNumber = 0;
//				back.setBackgroundResource(R.drawable.back);
//				return false;
			}
			background.setBackgroundColor(Color.parseColor(color[colorNumber]));
//			screenLight();
			setScreenBrightness(45 * colorNumber + 70);
		}
		return false;
	}

	private boolean isTouch = false;
	private boolean isSecondBack = false;
	
	private void setScreenBrightness(int value) {
		WindowManager.LayoutParams params = LightActivity.this.getWindow()
				.getAttributes();
		params.screenBrightness = value / 255f;
		LightActivity.this.getWindow().setAttributes(params);
	}
	
	TransitionDrawable transition1;
	TransitionDrawable transition2;
	  private void screenLight()
	  {
	    if(!isSecondBack) {
	    	if(!isTouch) {
	    		Resources res = getResources();  
	            transition1 = (TransitionDrawable) res  
	                    .getDrawable(R.drawable.transitonbg);  
//	    		background.setBackgroundResource(R.drawable.transitonbg);
//		    	transition1 = (TransitionDrawable)background.getBackground();
	            background.setBackgroundDrawable(transition1);
			    transition1.setCrossFadeEnabled(true);
		    	transition1.startTransition(500);
		    	isTouch = true;
		    	isSecondBack = true;
		    	System.out.println("第一次");
		    }else {
		    	System.out.println("第四次");
		    	transition1.reverseTransition(400);
		    	transition1.reverseTransition(400);
		    	isTouch = false;
		    }
	    	System.out.println("transition1: "+transition1);
	    }
	    else {
	    	if(isTouch) {
	    		Resources res = getResources();  
	            transition2 = (TransitionDrawable) res  
	                    .getDrawable(R.drawable.transitonbg2);  
	    		
//	    		background.setBackgroundResource(R.drawable.transitonbg2);
//		    	transition2 = (TransitionDrawable)background.getBackground();
	            background.setBackgroundDrawable(transition2);
			    transition2.setCrossFadeEnabled(true);
	    		System.out.println("第二次");
	    		transition2.startTransition(500);
		    	isTouch = false;
	    	}else {
	    		System.out.println("第三次");
	    		transition2.reverseTransition(400);
		    	isTouch = true;
		    	isSecondBack = false;
	    	}
	    	System.out.println("transition2: "+transition2);
	    }
	  }
}
